﻿using Analyse.DrawingPerformance.Model;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Analyse.DrawingPerformance.Contract
{
    public class WindowsMediaDrawingEngine : IDrawingEngine
    {
        public WindowsMediaDrawingEngine()
        {
        }

        public byte[] Draw(int width, int height, List<BaseDrawElement> drawElements)
        {
            using (var image = new Bitmap(width, height))
            using (var memoryStream = new MemoryStream())
            {
                var encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(Convert(image)));
                encoder.Save(memoryStream);
                return memoryStream.ToArray();
            }
        }

        public BitmapSource Convert(System.Drawing.Bitmap bitmap)
        {
            var bitmapData = bitmap.LockBits(
                new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
                System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat);

            var bitmapSource = BitmapSource.Create(
                bitmapData.Width, bitmapData.Height,
                bitmap.HorizontalResolution, bitmap.VerticalResolution,
                PixelFormats.Bgr24, null,
                bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride);

            bitmap.UnlockBits(bitmapData);
            return bitmapSource;
        }

        //private bool DrawImage(SKSurface surface, BaseDrawElement drawElement)
        //{
        //    var item = drawElement as ImageDrawElement;
        //    using (var paint = new SKPaint())
        //    {
        //        using (var bitmap = SKBitmap.Decode(item.ImagePath))
        //        {
        //            surface.Canvas.DrawBitmap(bitmap, item.X, item.Y, paint);
        //        }
        //    }

        //    return true;
        //}

        //private bool DrawText(SKSurface surface, BaseDrawElement drawElement)
        //{
        //    var item = drawElement as TextDrawElement;
        //    var color = ColorTranslator.FromHtml(item.Color);

        //    using (var paint = new SKPaint())
        //    {
        //        paint.TextSize = item.Size;
        //        paint.IsAntialias = true;
        //        paint.Color = new SKColor(color.R, color.G, color.B);
        //        paint.IsStroke = false;
        //        if (!string.IsNullOrEmpty(item.FontPath))
        //        {
        //            paint.Typeface = SKTypeface.FromFile(item.FontPath);
        //        }

        //        surface.Canvas.DrawText(item.Text, item.X, item.Y, paint);
        //    }

        //    return true;
        //}
    }
}
